<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

/**
 * 单商品价格减去固定折扣出售
 * $ 2010-05-04 17:06 $
 */
//class b2c_promotion_solutions_topercent2 implements b2c_interface_promotion_solution
class b2c_promotion_solutions_topercent2 implements b2c_interface_promotion_solution
{


    public $name = "以固定折扣出售(首批打折)"; // 名称   //@mo
    public $type = array('prefilter','cart'); // 应用范围 目前只有[预过滤(prefilter),购物车(cart)]
    public $desc_pre = '价格乘以';
    public $desc_post = '%折扣出售';
    private $description = '';
    public $desc_tag= '打折';

    //同种方案在同一商品上 适用 排他原则
    public $stop_rule_with_same_solution = true;



    public function __construct( $app ) {
        $this->app = $app;
        $this->name = app::get('b2c')->_($this->name);
        $this->desc_pre = app::get('b2c')->_($this->desc_pre);
        $this->desc_post = app::get('b2c')->_($this->desc_post);
    }



    /**
     * 优惠方案模板
     * @param array $aConfig // 设置信息(修改的时候传入)
     * @return string // 返回要输出的模板html
     */
    public function config($aData = array()) {


        return <<<EOF
{$this->desc_pre}<input name="action_solution[b2c_promotion_solutions_topercent2][percent]" vtype='required&&unsigned' value="{$aData['percent']}" />{$this->desc_post}
EOF;
    }

    /**
     * 优惠方案应用
     *
     * @param array $object  // 引用的一个商品信息
     * @param array $aConfig // 优惠的设置
     * @param array $cart_object // 购物车信息(预过滤的时候这个为null)
     * @return void // 引用处理了,没有返回值
     */
    //&$object,$config,$rule,&$cart_object=null
    //public function apply(&$object, &$aConfig,$rule,&$cart_object = null) {
      public function apply(&$object,&$aConfig,$rule,&$cart_object = null){

        $omath = kernel::single('ectools_math');
        $rulePercent = max(0, $aConfig['percent']);
        $rulePercent = min($rulePercent, 100);

        if(is_null($cart_object)) { // 商品预过滤
            $p = $rulePercent/100;
            $object['obj_items']['products'][0]['price']['buy_price'] = $omath->number_multiple( array($object['obj_items']['products'][0]['price']['buy_price'],$p) );
        } 
        else 
        {// 购物车里的处理
            $productQuantity = $object['obj_items']['products'][0]['quantity'];//当前个数
            $goodsQuantity = $object['quantity'];
            $qty = $productQuantity*$goodsQuantity;//每一份一个//表示当前商品的份数

            $productPrice = $object['obj_items']['products'][0]['price']['buy_price'];//购买价格
            
            //@mo
            $temp_goods_info= explode('_',$object['obj_ident']);//获取当前商品的goods_id
            $temp_goods_id = $temp_goods_info[1];
       
            if(!empty($temp_goods_id))
            {
               
                $firstvalue = $rule['conditions']['conditions'][0]['firstvalue'];//首批打折的个数

               
                //根据促销条件获取相应促销条件开始的时间
                $pre_rule = app::get('b2c')->model('sales_rule_order');
                $is_statue = "true";
                $filter_c = array('status|nequal'=>$is_statue,'rule_id'=>$rule['rule_id']);
                $all_promotion_rules = $pre_rule->getList('rule_id,conditions,from_time,to_time', $filter_c, 0, -1, 'rule_id ASC');
          

           
                $member_id = kernel::single('b2c_user_object')->get_member_id();
                $db_order = app::get('b2c')->model('orders');
                if(!empty($all_promotion_rules))
                {
                    $fromtime = $all_promotion_rules[0]['from_time'];
                    $totime = $all_promotion_rules[0]['to_time'];
                   
                    $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead//设置时间限制

               }
               else
               {
                    $filter = array('member_id'=>$member_id);//time: ,'createtime|bthan'=>$this_time
               }

                $this_member_all_orders = $db_order->getList('order_id,member_id', $filter, 0, -1, 'order_id ASC');
        

                $db_order_goods = app::get('b2c')->model('order_items');
                $gift_type = app::get('b2c')->_('product');

                $order_goods_nums = 0;//当前用户之前购买的数量
                foreach ($this_member_all_orders as $one_order) {
                    $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$temp_goods_id);
                    $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                    if(!empty($temp_goods))
                    {
                        $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                        
                    }
                     
                }

                //当前可以打折的个数
                $pre_can_dicount_goods_number = 0;

                if($order_goods_nums < $firstvalue)
                {
                    $pre_can_dicount_goods_number = $firstvalue - $order_goods_nums;//求出当前还可以打折的个数
                }
               $discountAmount = 0;//初始打折总价格为零
                if($pre_can_dicount_goods_number > 0)
                {
                    //$qty = $productQuantity*$goodsQuantity;//每一份一个//表示当前商品的份数
                  if($goodsQuantity >$pre_can_dicount_goods_number)//当前商品个数大于可以打折的数量
                  {
                       //计算出打折的优惠钱
                     $discountAmount = $productQuantity*$pre_can_dicount_goods_number *(1 - $rulePercent/100) * $productPrice;
                  }
                  else
                  {
                    $discountAmount = $productQuantity*$goodsQuantity *(1 - $rulePercent/100) * $productPrice;
                    //以当前的商品全部打折
                  }
             
                 
                }
                
            } 

            $object['discount_amount_order'] = $omath->number_plus( array($object['discount_amount_order'],$discountAmount) );
            //$this->desc_pre = '总价格乘以';
        }

        $this->setString($aConfig);
    }


    /*
        根据购物车，cart_object重新构造数组，去掉元素中的引用
     */
    public function delete_index_from_cart_object($cart_object)
    {
        $temp_cart_object = null;
          foreach ($cart_object as $key => $value) {
                  if($key == "object")
                  {
                    foreach ($value as $key2 => $value2) {
                       if($key2 == "goods")
                       {
                        $temp_cart_object[$key][$key2] = array();
                            foreach ($value2 as $key3 => $value3) {
                                if($key3 =="store")
                                {
                                     $temp_cart_object[$key][$key2][$key3] = array();
                                     foreach ($value3 as $key4 => $value4) {
                                        $temp_cart_object[$key][$key2][$key3][$key4] = $value4;
                                     }
                                }
                                else
                                $temp_cart_object[$key][$key2][$key3] = $value3;
                            }
                       }
                       else
                            $temp_cart_object[$key][$key2] = $value2;
                    }
                  }
                  else
                      $temp_cart_object[$key] = $value;

            }
        return $temp_cart_object;
    }
    /**
     * 优惠方案应用
     *
     * @param array $object  // 引用的一个商品信息
     * @param array $aConfig // 优惠的设置
     * @param array $cart_object // 购物车信息(预过滤的时候这个为null)
     * @return void // 引用处理了,没有返回值
     */
    public function apply_order(&$object, &$aConfig,$rule,&$cart_object = null) {
        if(is_null($cart_object)) return false;
        $omath = kernel::single('ectools_math');

        $rulePercent = max(0, $aConfig['percent']);
        $rulePercent = min($rulePercent, 100);

        $object['discount_amount_order'] += $omath->number_multiple(
                                                                array(
                                                                    ($cart_object['subtotal'] - $cart_object['discount_amount_prefilter']),
                                                                    (1 - $rulePercent/100)
                                                                )
                                                            );

        $this->desc_pre = app::get('b2c')->_('订单总价格乘以');
        $this->setString($aConfig);
    }






    public function setString($aData) {
        $this->description = $this->desc_pre . $aData['percent'] . $this->desc_post;
    }

    public function getString() {
        return $this->description;
    }



    public function get_status() {
        return true;
    }

    /**
	 * 校验参数是否正确
	 * @param mixed 需要校验的参数
	 * @param string error message
	 * @return boolean 是否成功
	 */
	public function verify_form($data=array(), &$msg='')
	{
		if (!$data) return true;

		/** 订单够满金额 **/
		if (!isset($data['action_solution']['b2c_promotion_solutions_topercent2']['percent']) || !$data['action_solution']['b2c_promotion_solutions_topercent2']['percent'])
		{
			$msg = app::get('b2c')->_('请指定订单固定折扣的金额！');
			return false;
		}

		if (!is_numeric($data['action_solution']['b2c_promotion_solutions_topercent2']['percent']) || $data['action_solution']['b2c_promotion_solutions_topercent2']['percent'] < 0 || $data['action_solution']['b2c_promotion_solutions_topercent2']['percent'] > 100)
		{
			$msg = app::get('b2c')->_('固定折扣必须是在0-100的数字！');
			return false;
		}
		/** end **/

		return true;
	}

    function get_desc_tag(){
        if(isset($this->cart_display)){
            $desc_tag['display'] = $this->cart_display;
        }else{
            $desc_tag['display'] = true;
        }
        $desc_tag['name'] = $this->desc_tag;
        return $desc_tag;
    }

}
